package com.example.demo.config;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Creat with IntelliJ IDEA
 * Description:
 * User:WZW
 * Date:2022-08-27
 * Time:9:58
 */
/*
返回true表示拦截判断通过，可以访问后面的接口
返回false则直接返回结果给前端
 */
@Component
public class LoginIntercept implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        // 1.得到httpsession对象
        HttpSession session = request.getSession(false);
        if (session != null && session.getAttribute("userinfo") != null) {
            // 已经登录
            return true;
        }
        // 未登录，跳转到登录页面
        response.sendRedirect("login.html");
        return false;
    }
}
